util.js

// 防抖函数
function debounce (fn, wait) {
  let t
  return () => {
    let context = this
    let args = arguments
    if (t) clearTimeout(t)
    t = setTimeout(() => {
      fn.apply(context, args)
    }, wait)
  }
}
function flatten (arr) { // 数组扁平化
  return arr.reduce((result, item) => {
    return result.concat(Array.isArray(item) ? flatten(item) : item)
  }, [])
}
function handleMulitePerson (sPerson) {
  console.log(44, sPerson.split(','))
  if (typeof sPerson == 'string') {
    let personArr = []
    sPerson.split(',').forEach(item => {
      let obj = { userCode: item.split('/')[0], userName: item.split('/')[1] }
      personArr.push(obj)
    })
    return personArr
  }
}

function uniqueArray (array, key) { // json数组根据key去重
  var result = [array[0]]
  for (var i = 1; i < array.length; i++) {
    var item = array[i]
    var repeat = false
    for (var j = 0; j < result.length; j++) {
      if (item[key] == result[j][key]) {
        repeat = true
        break
      }
    }
    if (!repeat) {
      result.push(item)
    }
  }
  return result
}
function setSessionStorage (key, val) {
  if (typeof (val) == 'object') {
    sessionStorage.setItem(key, JSON.stringify(val))
  } else {
    sessionStorage.setItem(key, val)
  }
}
function getSessionStorage (key) {
  return sessionStorage.getItem(key)
}
function removeStorage (key) {
  sessionStorage.removeItem(key)
}


function urlParams () { // 获取链接参数
  var str = location.search.length > 0 ? location.search.substring(1) : ''
  var items = str.length ? str.split('&') : []
  var args = {}
  var item = null
  var name = null
  var value = null
  for (let i = 0, len = items.length; i < len; i++) {
    item = items[i].split('=')
    name = decodeURIComponent(item[0])
    value = decodeURIComponent(item[1])
    if (name.length) {
      args[name] = value
    }
  };
  return args
}


function urlAfterParams () {
  var str = window.location.hash.length > 0 ? window.location.hash.substring(window.location.hash.indexOf('?') + 1) : ''
  var items = str.indexOf('&') > 0 ? str.split('&') : str.split('?')
  var args = {}
  var item = null
  var name = null
  var value = null
  for (let i = 0, len = items.length; i < len; i++) {
    item = items[i].split('=')
    name = decodeURIComponent(item[0])
    value = decodeURIComponent(item[1])
    if (name.length) {
      args[name] = value
    }
  };
  return args
}

function parseParams (url) {
  url = decodeURIComponent(url)
  var params = {}
  var idx = url.indexOf('?')
  if (idx > 0) {
    var queryStr = url.substring(idx + 1)
    if (queryStr.length > 0) {
      var arr = queryStr.split('&')
      for (let i = 0; i < arr.length; i++) {
        var pair = arr[i].split('=')
        if (pair.length == 2 && pair[0].length > 0) {
          params[pair[0]] = pair[1]
        }
      }
    }
  }
  return params
}


/**
 * 选人下拉框数据:username(userCode)
 */
function getSelectUserName (userName, userCode) {
  return userName + '(' + userCode + ')'
}

function getSelectLoginUser () {
  var userInfo = getLoginUserInfo()
  return getSelectUserName(userInfo.userName, userInfo.userId)
}

function getUserNameBySelectUserName (userName) {
  let i = userName.indexOf('(')
  return userName.substring(0, i)
}


/**
 * 登录用户信息
 * userId
 * userName
 * mobileNo
 * @returns {any}
 */
function getLoginUserInfo () {
  return JSON.parse(localStorage.getItem('userInfo'))
}

function getLoginUserCode () {
  return JSON.parse(localStorage.getItem('userInfo')).userId
}

export default {
  getNyr,
  getYDate,
  setSessionStorage,
  urlParams,
  urlAfterParams,
  parseParams,
  debounce,
  handleMulitePerson,
  uniqueArray,
  flatten,
  getSessionStorage,
  removeStorage,
  getSelectUserName,
  getSelectLoginUser,
  getLoginUserInfo,
  getLoginUserCode,
  getUserNameBySelectUserName
}

utils.js

var util = {
    getCookie: function (Name) {
        var search = Name + "=";
        if (document.cookie.length > 0) {
            var offset = document.cookie.indexOf(search);
            if (offset != -1) {
                offset += search.length;
                var end = document.cookie.indexOf(";", offset);
                if (end == -1) end = document.cookie.length;
                return unescape(document.cookie.substring(offset, end));
            } else
                return "";
        }
    },
    setCookie: function (name, value) {
        var Days = 30;
        var exp = new Date();
        exp.setTime(exp.getTime() + 1000 * 3600 * 24); //过期时间 2分钟
        document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/";
    },
    delCookie: function (name) {
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval = api.getCookie(name);
        if (cval != null) {
            document.cookie = name + "=" + cval + "; path=/;expires=" + exp.toGMTString();
        }
    },
    requestParams: function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    },

    getRequest: function () {
        var url = location.search; // 获取url中"?"符后的字串
        var theRequest = new Object();
        if (url.indexOf('?') >= 0) {
            let str = url.replace('?', ''),
                strArr = str.split('&');
            strArr.forEach(function (l) {
                let key = l.split('=')[0],
                    val = l.split('=')[1];
                theRequest[key] = val
            })
        }
        return theRequest;
    },
    decodeHTML: function (str) {
        if (!str) return '';
        return str.replace(/&lt;/g, '<').replace(/&amp;/g, "&").replace(/&gt;/g, ">").replace(/&quot;/g, "\"").replace(/&#39;/g, "'").replace(/&ldquo;/g, '“').replace(/&rdquo;/g, '”').replace(/&nbsp;/g, ' ')
    },
    filterHTML: function (msg) {
        var msg = msg.replace(/<\/?[^>]*>/g, ''); //去除HTML Tag
        msg = msg.replace(/[|]*\n/, '') //去除行尾空格
        msg = msg.replace(/&npsp;/ig, ''); //去掉npsp
        return msg;
    },
    urlAddParams: function (url, params) {
        var search = url.split('.html?').length > 1,
            link = '',
            result;
        for (var key in params) {
            var s = '&' + key + '=' + params[key];
            link += s
        }
        if (!!search) {
            result = url + link
        } else {
            result = url + '?' + link.slice(1)
        }
        return result
    },
    transParams: function (params) {
        let results = [];
        Object.keys(params).forEach(key => {
            let val = params[key];
            if (typeof val === 'undefined') {
                val = ''
            }
            results.push([key, encodeURIComponent(val)].join('='))
        });
        return results.join('&')
    },
    transPrice: function (num) {
        return (num / 100).toFixed(2) + '元'
    },
    transMinToHour(min) {
        return parseInt(min / 60);
    },
    checkPhone(tel) {
        var phoneReg = /^0?1[3|4|5|6|7|8|9][0-9]\d{8}$/;
        return phoneReg.test(tel)
    },
    checkCaptcha(captcha) {
        var capReg = /^[0-9]{6}$/;
        return capReg.test(captcha)
    },
    getTime: function () {
        return new Date().getTime();
    },
    saveData(key, val) {
        window.sessionStorage.setItem(key, val)
    },
    getData(key) {
        return window.sessionStorage.getItem(key)
    },
    delSaveData(key) {
        window.sessionStorage.removeItem(key)
    },
    isInWeChat() {
        var ua = window.navigator.userAgent.toLowerCase();
        return ua.indexOf('micromessenger') > -1;
    },
    isInApp: function () {
        var ua = window.navigator.userAgent.toLowerCase();
        return ua.indexOf('gloud') > -1 && window.gloud;
    },
    isInIos: function () {
        var ua = window.navigator.userAgent.toLowerCase();
        return ua.indexOf('iphone') > -1 || ua.indexOf('ipad') > -1;
    },
    h5CallIos(params) {
        // h5调用wkwebview
        window.webkit.messageHandlers.iOS.postMessage(params);
    },
    getToken: function () {
        if (this.isInApp()) {
            return window.gloud.getAccessToken()
        } else {
            var p = this.getRequest(),
                accessToken = "";
            if (!!p.accessToken) {
                accessToken = p.accessToken;
                this.setCookie('accessToken', accessToken);
            } else {
                accessToken = this.getCookie('accessToken');
            }
            return accessToken;
        }
        // return 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxODIwNTA5MDU2NV8xIn0.EMID6moIm9sZFNK20LBuHz1l60Bb82V9wbhCBwP6Pv0'
    },
    getVersion: function () {
        if (this.isInApp()) {
            return window.gloud.getAppVersion();
        } else {
            return '1.0';
        }
    },
    getChannelId: function () {
        var channel = "";
        if (this.isInApp()) {
            channel = window.gloud.getChannelId();
        } else {

            var p = this.getRequest();
            if (!!p.channelId) {
                channel = p.channelId;
                this.setCookie('channelId', channel);
            } else {
                channel = this.getCookie('channelId');
            }
        }
        return channel;
    },
    getChannel: function () {
        var channelId = this.getChannelId();
        return {
            channelType: '',
            channelId: channelId
        }
    },
    getChannels:function(){
        return {
            channelType: '',
            channelId: 90002
        }
    },
    getWoId: function () {
        return '';
    },
    getPageUrl(type, params) {
        let baseUrl = '';
        let config = {
            member: `member.html`, // 会员
            protocol: `protocol.html`, // 用户协议
            privacy: `privacy.html`, // 隐私协议
            pay: `pay.html`, // 支付,收银台
            infoLists: `infoLists.html`, // 资讯列表
            infoDetail: `infoDetail.html`, // 资讯详情
            about: `about.html`, // 关于我们
            apply: `applyPlay.html`, // 申请试玩
            benefits: `memberBenefits.html`, // 会员权益
            feedback: `feedback.html`, // 意见反馈
            login: `login.html`, // 用户登录
            controller: `controllerSetup.html`, // 手柄设置
            gameDetail: `gameDetail.html`
        };
        let parseParams = !!params ? this.transParams(params) : '',
            _url = type.indexOf('://') > -1 ? type : `${baseUrl}${config[type]}`,
            url = params ? `${_url}?${parseParams}` : _url;
        return url;
    },
    viewPage(type, params, isBarDark) {
        // let baseUrl = '';
        // let config = {
        //     member: `member.html`, // 会员
        //     protocol: `protocol.html`, // 用户协议
        //     privacy:`privacy.html`, // 隐私协议
        //     pay: `pay.html`, // 支付,收银台
        //     infoLists:`infoLists.html`, // 资讯列表
        //     infoDetail:`infoDetail.html`, // 资讯详情
        //     about: `about.html`, // 关于我们
        //     apply: `applyPlay.html`, // 申请试玩
        //     benefits: `memberBenefits.html`, // 会员权益
        //     feedback: `feedback.html`, // 意见反馈
        //     login:`login.html`, // 用户登录
        //     controller:`controllerSetup.html`,// 手柄设置
        // };
        // let parseParams = !!params ? this.transParams(params) : '',
        //     url = params ? `${baseUrl}${config[type]}?${parseParams}` : `${baseUrl}${config[type]}`;
        let url = this.getPageUrl(type, params);
        if (!!isBarDark) {
            this.setStatusBarDark();
        } else {
            this.setStatusBarLight();
        }
        window.location.href = url;
        // window.history.pushState({},'',url)
    },
    goLogin: function () {
        console.log('login')
        if (this.isInApp()) {
            window.gloud.gotoLoginScreen()
        } else {
            this.viewPage('login')
        }
    },
    backToApp: function () {
        if (this.isInApp()) {
            window.gloud.closePage()
        } else {
            console.log('回退到App')
        }
    },
    goBack: function () {
        var referrer = document.referrer,
            local = window.location.href;
        (referrer && referrer != local) ? (window.history.back()) : (this.backToApp())
        // var _history = window.history;
        // if(_history.length>1){
        //     window.history.back()
        // } else {
        //     this.backToApp()
        // }
    },

    getFullPath() {
        let pathName = function () {
            var arr = window.location.pathname.split('/');
            return arr.splice(0, arr.length - 1).join('/') + '/'
        }();
        let origin = window.location.origin
        return origin + pathName
    },

    // startGame(game) {
    //     console.log('start game : ', game);
    //     // alert(`'start game : ',${JSON.stringify(game)}`)
    //     if (this.isInApp()) {
    //         window.gloud.startGame(game.cpId, game.gameId, game.bigIcon, game.gameName, game.status + '', game.packageType + '', game.handShankImg || "");
    //     } else {
    //         Toast('暂不支持网页端访问哦~')
    //     }
    // },
    startGame(game){
        if (this.isInIos()) {
            this.h5CallIos({
                'type': 'startGame',
                "cpId": game.cpId,
                "game": game.gameId, 
            })
        }else{
            window.gloud.startGame(game.cpId, game.gameId)
        }
    },
    getPhone(){
        if (this.isInIos()) {
            this.h5CallIos({
                'type': 'getPhone', 
            })
        }else{
            return window.gloud.getPhone()
        }
    },
    startWebview(url) {
        if (this.isInApp()) {
            window.gloud.startWebview(url)
        } else {
            window.location.href = url;
        }
    },
    viewGameDetail(game) {
        let gameId = game.gameId,
            cpId = game.cpId;
        if (this.isInApp()) {

            console.log(' start view game detail ', gameId)
            window.gloud.gotoDetailScreen(gameId, cpId);
        } else {
            // Toast('暂不支持网页端访问哦~');
            let channelId = this.getChannelId();
            this.viewPage('gameDetail', {
                gameId,
                cpId,
                channelId
            });
        }
    },
    sendBuySuccessToApp(orderid) {
        if (this.isInApp()) {
            window.gloud.sendMsgToRN("PayResult", "success", orderid + "")
        }
    },

    sendBuyFailToApp(cpOrderid) {
        if (this.isInApp()) {
            window.gloud.payFail(false, cpOrderid)
        }
    },

    checkAppLogin() {
        if (this.isInApp()) {
            return window.gloud.isLogin();
        } else {
            return !!this.getToken()
        }
    },
    callTel(tel) {
        if (this.isInApp()) {
            window.gloud.callTel(tel);
        } else {
            let $a = document.createElement('a');
            $a.setAttribute('href', `tel:${tel}`);
            $a.click();
        }
    },
    getStatusBarHeight() {
        var height;
        if (this.isInApp()) {
            height = window.gloud.getStatusBarHeight();
        } else {
            height = 0;
        }
        return height;
    },
    setStatusBarTheme(isLight) {
        /**
         * 设置状态栏颜色
         *
         * @param isLight true-浅色背景深色字体, false-深色背景浅色字体, 默认为浅色背景深色字体
         */

        if (this.isInApp()) {
            window.gloud.setStatusBarTheme(isLight);
        }
    },
    setStatusBarDark() {
        console.log('set status bar dark');
        this.setStatusBarTheme(false)
    },
    setStatusBarLight() {
        console.log('set status bar light');
        this.setStatusBarTheme(true)
    },
    share(config) {
        if (this.isInApp()) {
            this.appShare(config)
        } else {
            console.log('web端访问', config)
        }
    },
    isWifi() {
        // return true;
        if (this.isInApp()) {
            return window.gloud.isWifi();
        } else {
            console.log('not in app');
            return false;
        }
    },
    appShare(config) {
        // APP内调用分享API
        console.log(config)
        let p = {
            title: config.title || '',
            icon: config.icon || '',
            url: config.url || '',
            text: config.text || ''
        }
        window.gloud.share(JSON.stringify(p))
    },
    taqPush(data) {
        console.log(data);
        !!_taq && _taq.push(data);
    },
    dotLogInit(data) {
        let ele = document.createElement('script'),
            me = this,
            isHttps = location.protocol.indexOf("https") > -1,
            siteId = '574100754',
            src = isHttps ? `https://h5.wostore.cn/wa.js?siteid=${siteId}` : `http://27.115.67.207:9090/wa.js?siteid=${siteId}`;
        ele.id = 'walog'
        ele.src = src;
        ele.onload = function () {
            me.taqPush(data)
        }
        document.querySelector('head').appendChild(ele)
    },
    dotLog(key, action, actId, chid) { // 页面打点
        console.log('dotLog=', key, action)
        var urlParams = this.getRequest();
        var logData = new Object;
        logData.ch = urlParams.chid || chid || 'gloudpush';
        logData.act_id = !!actId ? actId : 'YYX_TGY';

        logData.category = key;
        logData.action = action;
        if (!!window._taq) {
            // _taq.push(logData);
            this.taqPush(logData);

        } else {
            this.dotLogInit(logData)
        }
    },

    reloadUrl(url) {
        if (this.isInApp()) {
            window.gloud.reload(url);
        }
    }

}
export default util;
防抖函数
 debounce(fn, delay) {
      let timer = 0
      return function () {
        if (timer) clearTimeout(timer)
        timer = setTimeout(() => {
          fn.apply(this, arguments)
          timer = 0
        }, delay)
      }
    },


  this.$refs.input.addEventListener(
      'keyup',
      this.debounce(() => {
        console.log('防抖')
      })
    )

防抖加强版

 debounce (fn, time, immediate) {
      let timer = null
      let debounced = function () {
        let context = this
        let args = arguments
        if (timer) clearTimeout(timer)
        if (immediate) {
          let callNow = !timer
          timer = setTimeout(() => {
            timer = null
          }, time || 500)
          if (callNow) fn.apply(context, args)
        } else {
          timer = setTimeout(() => {
            fn.apply(context, args)
          }, time || 500)
        }
      }
      debounced.cancel = function () {
        clearTimeout(timer)
        timer = null
      }
      return debounced
    }

let set = this.debounce(() => {console.log('hello')}, 500,true)
document.getElementById('div').addEventListener('click', set)
document.getElementById('div').addEventListener('click', function(){set.cancel()})

HappyCodingTop
526 声望847 粉丝

Talk is cheap, show the code!!